import { loginIgnore } from '@/utils/router-utils'
import { checkAuthorization } from '@/request/auth'

/**
 * 路由导航守卫的配置文件
 * 
 * @author LiSong
 * @date 2022-5-16 11:24:59
 */
const loginGuard = (to, from, next, options) => {
  const { message } = options
  if (!loginIgnore.includes(to) && !checkAuthorization()) {
    message.warning('登录已失效，请重新登录')
    next({path: '/login'})
  } else {
    next()
  }
}

/**
 * 混合导航模式下一级菜单跳转重定向
 * @param to
 * @param from
 * @param next
 * @param options
 * @returns {*}
 */
 const redirectGuard = (to, from, next, options) => {
  const {store} = options
  const getFirstChild = (routes) => {
    const route = routes[0]
    if (!route.children || route.children.length === 0) {
      return route
    }
    return getFirstChild(route.children)
  }
  if (store.state.settings.layout === 'mix') {
    const firstMenu = store.getters['settings/firstMenu']
    if (firstMenu.find(item => item.fullPath === to.fullPath)) {
      store.commit('settings/setActivatedFirst', to.fullPath)
      const subMenu = store.getters['settings/subMenu']
      if (subMenu.length > 0) {
        const redirect = getFirstChild(subMenu)
        return next({path: redirect.fullPath})
      }
    }
  }
  next()
}


export default {
  beforeEach: [ loginGuard, redirectGuard ],
  afterEach: []
}

